package com.shxzz.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shxzz.shortlink.admin.common.biz.user.UserContext;
import com.shxzz.shortlink.admin.common.convention.exception.ClientException;
import com.shxzz.shortlink.admin.common.convention.exception.ServiceException;
import com.shxzz.shortlink.admin.common.enums.UserErrorCode;
import com.shxzz.shortlink.admin.dao.entity.UserDO;
import com.shxzz.shortlink.admin.dao.mapper.UserMapper;
import com.shxzz.shortlink.admin.dto.req.UserLoginReqDTO;
import com.shxzz.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.shxzz.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.shxzz.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.shxzz.shortlink.admin.dto.resp.UserRespDTO;
import com.shxzz.shortlink.admin.service.GroupService;
import com.shxzz.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;

import static com.shxzz.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static com.shxzz.shortlink.admin.common.constant.RedisCacheConstant.USER_LOGIN_INFO_KEY;


/**
 * @author shxzz
 * @create 2023-12-08-18:39
 * @description 用户接口实现
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    private final GroupService groupService;

    private final UserMapper userMapper;

    private final RBloomFilter<String> userRegisterCachePenetrationRBloomFilter;

    private final RedissonClient redissonClient;

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public UserRespDTO getUserByUserName(String username) {

        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username);

        UserDO userDO = userMapper.selectOne(queryWrapper);

        if (userDO == null) {
            throw new ClientException(UserErrorCode.USER_NULL);
        }

        UserRespDTO result = new UserRespDTO();

        BeanUtils.copyProperties(userDO, result);

        return result;
    }

    @Override
    public Boolean hasUsername(String username) {
        return userRegisterCachePenetrationRBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO requireParam) {
        // TODO 参数校验

        // 1. 查询布隆过滤器中是否存在该用户名
        Boolean hasUsername = hasUsername(requireParam.getUsername());
        if (Boolean.TRUE.equals(hasUsername)) {
            throw new ClientException(UserErrorCode.USER_NAME_EXIST);
        }

        // 2. 保存用户信息
        RLock userRegisterLock = redissonClient
                .getLock(LOCK_USER_REGISTER_KEY + requireParam.getUsername());

        if (!userRegisterLock.tryLock()) {
            throw new ClientException(UserErrorCode.USER_NAME_EXIST);
        }

        try {
            UserDO userDO = BeanUtil.toBean(requireParam, UserDO.class);

            try {
                int insert = userMapper.insert(userDO);
                if (insert < 1) {
                    throw new ClientException(UserErrorCode.USER_SAVE_ERROR);
                }
            } catch (DuplicateKeyException e) {
                throw new ClientException(UserErrorCode.USER_EXIST);
            }

            // 3. 向布隆过滤器中添加该用户名
            userRegisterCachePenetrationRBloomFilter.add(userDO.getUsername());
        } finally {
            userRegisterLock.unlock();
        }

        try {
            groupService.registerGroup(requireParam.getUsername(), "默认分组");
        } catch (Exception e) {
            throw new ServiceException("默认分组创建失败");
        }
    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requireParam) {
        // 1. 查询用户信息
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requireParam.getUsername())
                .eq(UserDO::getDelFlag, 0);

        UserDO userDO = userMapper.selectOne(queryWrapper);

        if (userDO == null) {
            throw new ClientException(UserErrorCode.USER_NULL);
        }

        // 2. 校验密码
        if (!userDO.getPassword().equals(requireParam.getPassword())) {
            throw new ClientException("用户密码错误");
        }

        String userLoginInfoKey = USER_LOGIN_INFO_KEY + requireParam.getUsername();
        // 3. 判断登陆状态，已登录直接返回原 token
        Boolean hasKey = stringRedisTemplate.hasKey(userLoginInfoKey);
        if (Boolean.TRUE.equals(hasKey)) {
            stringRedisTemplate.expire(userLoginInfoKey, 30L, TimeUnit.MINUTES);
            String token = Optional
                    .ofNullable(stringRedisTemplate.opsForHash().get(userLoginInfoKey, "token"))
                    .map(Object::toString)
                    .orElseThrow(() -> new ServiceException("用户登录错误"));
            return new UserLoginRespDTO(token);
        }

        // 4. 生成 token 返回
        String token = UUID.randomUUID().toString().replace("-", "");

        Map<String, String> userLoginInfo = new HashMap<>();
        userLoginInfo.put("token", token);
        userLoginInfo.put(token, JSON.toJSONString(userDO));

        stringRedisTemplate.opsForHash().putAll(userLoginInfoKey, userLoginInfo);
        stringRedisTemplate.expire(userLoginInfoKey, 30L, TimeUnit.MINUTES);

        return new UserLoginRespDTO(token);
    }

    @Override
    public void update(UserUpdateReqDTO requireParam) {
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class)
                .eq(UserDO::getUsername, UserContext.getUser().getUsername())
                .eq(UserDO::getDelFlag, 0);

        int update = userMapper.update(BeanUtil.toBean(requireParam, UserDO.class), updateWrapper);

        if(update != 1) {
            throw new ServiceException("用户更新错误");
        }
    }

    @Override
    public void logout() {
        Boolean result = stringRedisTemplate.delete(USER_LOGIN_INFO_KEY + UserContext.getUser().getUsername());

        if(Boolean.FALSE.equals(result)) {
            throw new ServiceException("用户登出失败");
        }
    }

}
